package com.example.testapp;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.NumberPicker;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import androidx.core.content.ContextCompat;

import com.example.testapp.api.ApiClient;
import com.example.testapp.api.ApiService;
import com.example.testapp.model.BookData;
import com.example.testapp.utils.GetCategoryIcon;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class HomeActivity extends AppCompatActivity {

    private static final String TAG = "HomeActivity";
    // 添加请求码常量
    private static final int REQUEST_CODE_DETAIL = 1001;
    private LocalDate currentDate;
    private TextView todayExpenseTextView;
    private TextView monthExpenseTextView;
    private TextView monthIncomeTextView;
    private TextView titleMonth;
    private YearMonth selectedYearMonth;
    private int userId;

    private LinearLayout recordContainer;
    private LayoutInflater inflater;
    private static final DateTimeFormatter YEAR_MONTH_FORMATTER = DateTimeFormatter.ofPattern("yyyy年M月");
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy.MM.dd");
    private static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("HH:mm");

    private ImageView userIcon;
    private CardView tutorialBubble; // 新手引导提示
    private TextView monthRecordCountTextView; // 本月记账数显示

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        // 找到视图
        initViews();

        // 获取当前日期
        currentDate = LocalDate.now();
        selectedYearMonth = YearMonth.from(currentDate);
        // 定义日期格式化器
        String formattedDate = currentDate.format(YEAR_MONTH_FORMATTER);

        // 更新 titleMonth 的文本
        titleMonth.setText(formattedDate);
        Log.d(TAG, "onCreate: Title month set to " + formattedDate);

        // 获取用户 ID，这里假设从登录成功后的 UserResponse 中获取，你可以根据实际情况修改
        userId = getIntent().getIntExtra("userId", 0);
        Log.d(TAG, "onCreate: Received userId: " + userId);


        // 为 titleMonth 添加点击事件监听器
        titleMonth.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "titleMonth onClick: Click event triggered, showing year-month picker");
                showYearMonthPicker();
            }
        });

        // 初始化蓝色统计卡片的内容
        updateStatsCard(selectedYearMonth);
        updateTodayExpense(); // 新增：单独更新今日支出
    }

    private void initViews() {
        titleMonth = findViewById(R.id.titleMonth);
        todayExpenseTextView = findViewById(R.id.todayExpense);
        monthExpenseTextView = findViewById(R.id.monthExpense);
        monthIncomeTextView = findViewById(R.id.monthIncome);
        recordContainer = findViewById(R.id.recordContainer);
        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(v -> {
            AddCardBottomSheetFragment addCard = new AddCardBottomSheetFragment();
            // 传递userId
            Bundle args = new Bundle();
            args.putInt("userId", userId);
            addCard.setArguments(args);
            addCard.show(getSupportFragmentManager(), "AddCardBottomSheet");
        });
        inflater = LayoutInflater.from(this);
        userIcon = findViewById(R.id.userIcon);
        userIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "用户头像被点击，跳转到用户详情页，userId: " + userId);
                Intent intent = new Intent(HomeActivity.this, UserDetailActivity.class);
                intent.putExtra("userId", userId);
                startActivity(intent);
            }
        });

        // 初始化本月记账数显示
        monthRecordCountTextView = findViewById(R.id.monthRecordCount);

        // 初始化新手引导提示
        tutorialBubble = findViewById(R.id.tutorialBubble);
        tutorialBubble.setOnClickListener(v -> {
            // 点击后隐藏提示
            tutorialBubble.setVisibility(View.GONE);
        });
    }

    /**
     * 刷新页面数据（包括月度统计和今日支出）
     */
    public void refreshData() {
        // 刷新月度统计数据
        updateStatsCard(selectedYearMonth);
        // 刷新今日支出
        updateTodayExpense();
    }

    /**
     * 显示年月选择器对话框
     */
    private void showYearMonthPicker() {
        // 获取当前年月
        Calendar calendar = Calendar.getInstance();
        int currentYear = calendar.get(Calendar.YEAR);

        // 初始选中值
        int selectedYear = selectedYearMonth.getYear();
        int selectedMonth = selectedYearMonth.getMonthValue();

        // 加载自定义布局
        View dialogView = getLayoutInflater().inflate(R.layout.year_month_picker_dialog, null);
        NumberPicker yearPicker = dialogView.findViewById(R.id.yearPicker);
        NumberPicker monthPicker = dialogView.findViewById(R.id.monthPicker);

        // 设置 yearPicker
        int minYear = 2000; // 可根据你项目数据范围调整
        yearPicker.setMinValue(minYear);
        yearPicker.setMaxValue(currentYear);
        yearPicker.setValue(selectedYear);

        // 设置 monthPicker
        monthPicker.setMinValue(1);
        monthPicker.setMaxValue(12);
        monthPicker.setValue(selectedMonth);

        // 构造对话框
        new MaterialAlertDialogBuilder(this)
                .setTitle("选择年月")
                .setView(dialogView)
                .setPositiveButton("确定", (dialog, which) -> {
                    int year = yearPicker.getValue();
                    int month = monthPicker.getValue();
                    selectedYearMonth = YearMonth.of(year, month);
                    String formattedDate = selectedYearMonth.format(DateTimeFormatter.ofPattern("yyyy年M月"));
                    titleMonth.setText(formattedDate);
                    updateStatsCard(selectedYearMonth); // 只更新月度数据
                    // 不需要更新今日支出，因为它始终显示当前日期
                })
                .setNegativeButton("取消", null)
                .show();
    }

    /**
     * 更新统计卡片数据（月度支出/收入）
     * @param yearMonth 选中的年月对象
     */
    private void updateStatsCard(YearMonth yearMonth) {
        Log.i(TAG, "updateStatsCard: Fetching data for yearMonth=" + yearMonth);

        // 调用 API 获取对应月份的收支数据
        ApiService apiService = ApiClient.getClient().create(ApiService.class);
        Call<List<BookData>> call = apiService.listByYearMonth(userId, yearMonth.toString());
        Log.d(TAG, "updateStatsCard: API request sent for userId=" + userId +
                ", yearMonth=" + yearMonth);

        call.enqueue(new Callback<List<BookData>>() {
            @Override
            public void onResponse(Call<List<BookData>> call, Response<List<BookData>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    Log.d(TAG, "onResponse: API call successful, received " +
                            response.body().size() + " records");
                    List<BookData> bookDataList = response.body();
                    calculateMonthlyStats(bookDataList, yearMonth);
                    updateRecordCards(bookDataList);

                    // 更新本月记账数量
                    updateRecordCount(bookDataList);
                } else {
                    Log.e(TAG, "onResponse: API call failed. Code: " +
                            response.code() + ", Message: " + response.message());
                }
            }

            @Override
            public void onFailure(Call<List<BookData>> call, Throwable t) {
                Log.e(TAG, "网络错误: " + t.getMessage());
            }
        });
    }

    /**
     * 更新今日支出数据
     */
    private void updateTodayExpense() {
        // 获取当前年月（今天所在的年月）
        YearMonth currentYearMonth = YearMonth.from(currentDate);

        ApiService apiService = ApiClient.getClient().create(ApiService.class);
        Call<List<BookData>> call = apiService.listByYearMonth(userId, currentYearMonth.toString());

        call.enqueue(new Callback<List<BookData>>() {
            @Override
            public void onResponse(Call<List<BookData>> call, Response<List<BookData>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    double todayExpense = calculateTodayExpense(response.body());
                    todayExpenseTextView.setText(String.format("%.2f", todayExpense));

                    // 检查今日支出是否为0，显示引导提示
                    if (todayExpense == 0) {
                        showTutorialBubble();
                    } else {
                        hideTutorialBubble();
                    }

                    Log.d(TAG, "updateTodayExpense: Today's expense updated to " + todayExpense);
                }
            }

            @Override
            public void onFailure(Call<List<BookData>> call, Throwable t) {
                Log.e(TAG, "获取今日支出失败: " + t.getMessage());
            }
        });
    }

    // 显示新手引导提示
    private void showTutorialBubble() {
        runOnUiThread(() -> {
            if (tutorialBubble != null) {
                tutorialBubble.setVisibility(View.VISIBLE);

                // 7秒后自动隐藏提示
                new Handler().postDelayed(() -> {
                    if (tutorialBubble != null) {
                        tutorialBubble.setVisibility(View.GONE);
                    }
                }, 7000);
            }
        });
    }

    // 隐藏新手引导提示
    private void hideTutorialBubble() {
        runOnUiThread(() -> {
            if (tutorialBubble != null && tutorialBubble.getVisibility() == View.VISIBLE) {
                tutorialBubble.setVisibility(View.GONE);
            }
        });
    }

    /**
     * 计算并返回指定月份的收支统计数据
     * @param bookDataList 账本数据列表
     * @param yearMonth 目标年月
     */
    private void calculateMonthlyStats(List<BookData> bookDataList, YearMonth yearMonth) {
        Log.d(TAG, "calculateMonthlyStats: Calculating stats for " +
                bookDataList.size() + " records in " + yearMonth);

        double monthExpenseAmount = 0;
        double monthIncomeAmount = 0;

        for (BookData bookData : bookDataList) {
            LocalDateTime bookDateTime = LocalDateTime.parse(bookData.getBookDate());
            LocalDate bookDate = bookDateTime.toLocalDate();

            if (bookDate.getYear() == yearMonth.getYear() &&
                    bookDate.getMonthValue() == yearMonth.getMonthValue()) {
                if (bookData.getType() == 1) { // 支出
                    monthExpenseAmount += bookData.getPrice().doubleValue();
                } else if (bookData.getType() == 0) { // 收入
                    monthIncomeAmount += bookData.getPrice().doubleValue();
                }
            }
        }

        // 更新月度统计数据
        monthExpenseTextView.setText(String.format("%.2f", monthExpenseAmount));
        monthIncomeTextView.setText(String.format("%.2f", monthIncomeAmount));
    }

    /**
     * 计算并返回当日支出总额
     * @param bookDataList 账本数据列表
     * @return 当日支出总金额
     */
    private double calculateTodayExpense(List<BookData> bookDataList) {
        Log.d(TAG, "calculateTodayExpense: Calculating today's expense for " + bookDataList.size() + " records");
        double todayExpenseAmount = 0;

        for (BookData bookData : bookDataList) {
            LocalDateTime bookDateTime = LocalDateTime.parse(bookData.getBookDate());
            LocalDate bookDate = bookDateTime.toLocalDate();

            if (bookDate.isEqual(currentDate) && bookData.getType() == 1) {
                todayExpenseAmount += bookData.getPrice().doubleValue();
            }
        }

        return todayExpenseAmount;
    }

    /**
     * 更新记录卡片容器中的记账记录视图
     * @param bookDataList 账本数据列表
     */
    private void updateRecordCards(List<BookData> bookDataList) {
        Log.d(TAG, "updateRecordCards: Updating record cards for " + bookDataList.size() + " records");
        // 清除现有视图
        recordContainer.removeAllViews();

        // 按日期分组
        Map<LocalDate, List<BookData>> recordsByDate = new LinkedHashMap<>();

        for (BookData bookData : bookDataList) {
            LocalDateTime dateTime = LocalDateTime.parse(bookData.getBookDate());
            LocalDate date = dateTime.toLocalDate();

            if (!recordsByDate.containsKey(date)) {
                recordsByDate.put(date, new ArrayList<>());
            }
            recordsByDate.get(date).add(bookData);
        }

        // 按日期倒序排序（最近日期在前）
        List<LocalDate> sortedDates = new ArrayList<>(recordsByDate.keySet());
        Collections.sort(sortedDates, Collections.reverseOrder());

        // 为每天创建卡片
        for (LocalDate date : sortedDates) {
            View cardView = createRecordCard(date, recordsByDate.get(date));
            recordContainer.addView(cardView);
        }
        Log.i(TAG, "updateRecordCards: Record cards updated");
    }

    /**
     * 创建单日记录卡片视图
     * @param date 记录日期
     * @param records 当日记录列表
     * @return 组装好的卡片视图
     */
    private View createRecordCard(LocalDate date, List<BookData> records) {
        // 创建卡片视图
        View cardView = inflater.inflate(R.layout.item_record_card, recordContainer, false);

        // 设置日期
        TextView dateText = cardView.findViewById(R.id.text_date);
        dateText.setText(date.format(DATE_FORMATTER));

        // 计算当天收支
        double expense = 0;
        double income = 0;

        for (BookData record : records) {
            if (record.getType() == 1) {
                expense += record.getPrice().doubleValue();
            } else {
                income += record.getPrice().doubleValue();
            }
        }

        // 设置收支
        TextView expenseText = cardView.findViewById(R.id.text_expense);
        TextView incomeText = cardView.findViewById(R.id.text_income);
        expenseText.setText(String.format("支%.2f", expense));
        incomeText.setText(String.format("收%.2f", income));

        // 获取记录容器
        LinearLayout recordsContainer = cardView.findViewById(R.id.container_records);

        // 添加单个记录视图
        for (BookData record : records) {
            View recordView = createSingleRecord(record);
            recordsContainer.addView(recordView);
        }

        return cardView;
    }

    /**
     * 创建单条记录视图
     * @param record 账本数据对象
     * @return 组装好的记录视图
     */
    private View createSingleRecord(BookData record) {
        View recordView = inflater.inflate(R.layout.item_single_record, null);

        // 设置图标（根据类别）
        ImageView icon = recordView.findViewById(R.id.image_icon);
        icon.setImageResource(getIconForCategory(record.getCategory()));

        // 设置类别
        TextView category = recordView.findViewById(R.id.text_category);
        category.setText(record.getCategory());

        // 设置时间
        TextView time = recordView.findViewById(R.id.text_time);
        LocalDateTime dateTime = LocalDateTime.parse(record.getBookDate());
        time.setText(dateTime.format(TIME_FORMATTER));

        // 设置来源（使用备注字段）
        TextView source = recordView.findViewById(R.id.text_source);
        source.setText(record.getRemark() != null ? record.getSource() : "无");

        // 设置金额
        TextView amount = recordView.findViewById(R.id.text_amount);
        String amountPrefix = record.getType() == 1 ? "-" : "+";
        amount.setText(amountPrefix + String.format("%.2f", record.getPrice().doubleValue()));
        amount.setTextColor(ContextCompat.getColor(this,
                record.getType() == 1 ? R.color.expense_red : R.color.income_green));

        // 添加点击和长按事件监听
        recordView.setOnClickListener(v -> {
            Log.d(TAG, "createSingleRecord: 记录点击: 跳转到详情页面, 记录ID=" + record.getId());
            Log.d(TAG, "createSingleRecord: 检测类型（收入：0 支出：1）: " + record.getType());
            // 点击跳转到详情页面
            Intent intent = new Intent(HomeActivity.this, DetailActivity.class);
            // 添加用户ID参数
            intent.putExtra("user_id", userId);
            // 传递记录数据
            intent.putExtra("record_id", record.getId());
            intent.putExtra("record_type", record.getType());
            intent.putExtra("record_category", record.getCategory());
            intent.putExtra("record_price", record.getPrice().doubleValue());
            intent.putExtra("record_date", record.getBookDate());
            intent.putExtra("record_remark", record.getRemark());
            intent.putExtra("record_source", record.getSource());
            startActivityForResult(intent, REQUEST_CODE_DETAIL);
        });

        recordView.setOnLongClickListener(v -> {
            Log.d(TAG, "记录长按: 显示删除对话框, 记录ID=" + record.getId());

            // 长按添加缩放和透明度动画
            ObjectAnimator scaleX = ObjectAnimator.ofFloat(recordView, "scaleX", 1f, 0.95f);
            ObjectAnimator scaleY = ObjectAnimator.ofFloat(recordView, "scaleY", 1f, 0.95f);
            ObjectAnimator alpha = ObjectAnimator.ofFloat(recordView, "alpha", 1f, 0.7f);

            scaleX.setDuration(200);
            scaleY.setDuration(200);
            alpha.setDuration(200);

            scaleX.setInterpolator(new AccelerateDecelerateInterpolator());
            scaleY.setInterpolator(new AccelerateDecelerateInterpolator());
            alpha.setInterpolator(new AccelerateDecelerateInterpolator());

            AnimatorSet animatorSet = new AnimatorSet();
            animatorSet.playTogether(scaleX, scaleY, alpha);
            animatorSet.start();

            // 长按显示删除确认对话框
            MaterialAlertDialogBuilder dialogBuilder = new MaterialAlertDialogBuilder(HomeActivity.this)
                    .setTitle("删除记录")
                    .setMessage("确定要删除这条记录吗？")
                    .setPositiveButton("删除", (dialog, which) -> {
                        Log.d(TAG, "用户确认删除, 记录ID=" + record.getId());
                        deleteBookRecord(record.getId());
                        restoreRecordView(recordView); // 删除后恢复缩放和透明度
                    })
                    .setNegativeButton("取消", (dialog, which) -> {
                        Log.d(TAG, "用户取消删除, 记录ID=" + record.getId());
                        // 取消后恢复缩放和透明度
                        restoreRecordView(recordView);
                    })
                    .setOnCancelListener(new DialogInterface.OnCancelListener() {
                        @Override
                        public void onCancel(DialogInterface dialog) {
                            Log.d(TAG, "对话框取消, 记录ID=" + record.getId());
                            // 对话框取消后恢复缩放和透明度
                            restoreRecordView(recordView);
                        }
                    });
            dialogBuilder.show();
            return true;
        });

        return recordView;
    }

    /**
     * 处理活动返回结果（详情页返回时刷新数据）
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_DETAIL) {
            // 无论成功失败都刷新数据（根据实际需求调整）
            refreshData();
        }
    }

    /**
     * 删除指定记账记录
     * @param recordId 要删除的记录ID
     */
    private void deleteBookRecord(int recordId) {
        Log.d(TAG, "删除记录: 开始删除记录, ID=" + recordId);

        ApiService apiService = ApiClient.getClient().create(ApiService.class);
        Call<Void> call = apiService.deleteBookData(recordId);
        call.enqueue(new Callback<Void>() {
            @Override
            public void onResponse(Call<Void> call, Response<Void> response) {
                if (response.isSuccessful()) {
                    Log.d(TAG, "删除成功: 记录ID=" + recordId + ", HTTP状态码=" + response.code());
                    Toast.makeText(HomeActivity.this, "记录已删除", Toast.LENGTH_SHORT).show();
                    refreshData(); // 刷新数据
                } else {
                    Log.e(TAG, "删除失败: 记录ID=" + recordId +
                            ", HTTP状态码=" + response.code() +
                            ", 错误信息=" + response.message());
                    Toast.makeText(HomeActivity.this, "删除失败: " + response.code(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<Void> call, Throwable t) {
                Log.e(TAG, "删除失败: 网络错误, 记录ID=" + recordId +
                        ", 错误信息=" + t.getMessage(), t);
                Toast.makeText(HomeActivity.this, "网络错误: " + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 更新本月记账数量显示
     * @param bookDataList 账本数据列表
     */
    private void updateRecordCount(List<BookData> bookDataList) {
        int recordCount = bookDataList.size();
        String text = String.format(getString(R.string.month_record_count), recordCount);
        monthRecordCountTextView.setText(text);
        Log.d(TAG, "updateRecordCount: Displaying record count: " + recordCount);
    }

    /**
     * 恢复记录视图的原始状态（取消长按效果）
     * @param recordView 需要恢复的记录视图
     */
    private void restoreRecordView(View recordView) {
        ObjectAnimator restoreScaleX = ObjectAnimator.ofFloat(recordView, "scaleX", 0.95f, 1f);
        ObjectAnimator restoreScaleY = ObjectAnimator.ofFloat(recordView, "scaleY", 0.95f, 1f);
        ObjectAnimator restoreAlpha = ObjectAnimator.ofFloat(recordView, "alpha", 0.7f, 1f);

        restoreScaleX.setDuration(200);
        restoreScaleY.setDuration(200);
        restoreAlpha.setDuration(200);

        restoreScaleX.setInterpolator(new AccelerateDecelerateInterpolator());
        restoreScaleY.setInterpolator(new AccelerateDecelerateInterpolator());
        restoreAlpha.setInterpolator(new AccelerateDecelerateInterpolator());

        AnimatorSet restoreAnimatorSet = new AnimatorSet();
        restoreAnimatorSet.playTogether(restoreScaleX, restoreScaleY, restoreAlpha);
        restoreAnimatorSet.start();
    }

    /**
     * 根据类别名称获取对应图标资源ID
     * @param category 记账类别名称
     * @return 对应的图标资源ID
     */
    private int getIconForCategory(String category) {
        return GetCategoryIcon.getIconId(category);
    }
}